﻿using COFE.Core.Entry;
using COFE.Core.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace COFE.Core
{
    public class ResourceListAttribute : NotCachableAttribute
    {

        #region Constructor

        /// <summary>
        /// Constructor for filting the selected properties.
        /// </summary>
        /// <param name="properties"></param>
        public ResourceListAttribute(params object[] properties)
            : this(MatchMode.Any, new AnyPropertyFilter(properties))
        {
        }


        /// <summary>
        /// COnstructor for filting the property list using property filter.
        /// </summary>
        /// <param name="options"></param>
        /// <param name="matchMode"></param>
        /// <param name="filters"></param>
        public ResourceListAttribute(MatchMode matchMode = MatchMode.All, params IPropertyFilter[] filters)        
        {            
            _matchMode = matchMode;
            _filters = filters;
        }
               

        #endregion

        #region Methods

        public IEnumerable<object> FilterProperties(IEnumerable<object> allProperties)
        {
            return from p in allProperties where FilterUtils2.MatchPropertyFilters(p, _matchMode, _filters) select p;
        }

        #endregion

        #region Data
        
        MatchMode _matchMode = MatchMode.All;
        IPropertyFilter[] _filters;

        #endregion

        #region Public Properties

        public MatchMode MatchMode { get { return _matchMode; } }
        public IPropertyFilter[] Filters { get { return _filters; } }

        #endregion
    }

    public static class ResourceListAttributeExtension
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="resourceListProperty">The property with ResourceListAttribute attached on it, which included IPropertyFilters to filter allProperties</param>
        /// <param name="allProperties">Properties to be filtered.</param>
        /// <returns></returns>
        public static IEnumerable<object> GetFilteredProperties(object resourceListProperty, IEnumerable<object> allProperties)
        {
            var rla = EnumUtils<ResourceListAttribute>.FindAttribute(resourceListProperty);
            if (rla == null)
                throw new ArgumentException(resourceListProperty.ToString() + " does not implements ResourceListAttribute.");
            return rla.FilterProperties(allProperties);
        }
    }
}
